package com.hz.controller;

import com.alibaba.fastjson.JSONObject;
import com.hz.dao.EarningsDao;
import com.hz.dao.UserDao;
import com.hz.pojo.Earnings;
import com.hz.pojo.PicUploadResult;
import com.hz.pojo.User;
import com.hz.service.PicUploadService;
import com.hz.service.impl.UserServiceImpl;
import com.hz.utils.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserDao userDao;
    @Resource
    UserServiceImpl userService;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @RequestMapping("/userinfo")
    public MassageJsons getUserInfo(User user){

        //从Redis查询是否有该用户
        String jsonuser = stringRedisTemplate.opsForValue().get(user.getOpen_id());
        //转换为对象
        User users = JSONObject.parseObject(jsonuser,User.class);
        //判断对象是否为空
        if(users!=null){
            try {
                //更新最后一次登录时间
                userService.updLlastLoginTime(users.getOpen_id(),DateUtils.getCurrentTime());
                //把更新的用户从新存入Redis
                stringRedisTemplate.opsForValue().set(users.getOpen_id(),JSONObject.toJSONString(users));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new MassageJsons("0","登录成功",users);
        }else {
            //添加创建时间
            user.setUser_creattime(DateUtils.getCurrentTime());
            //添加最后一次登录使劲啊
            user.setUser_last_login_time(DateUtils.getCurrentTime());
            //添加代理id
            if(user.getProxy_id()<3){user.setProxy_id(user.getProxy_id()+1);}
            //添加第一次注册的用户信息
            userService.addUserInfo(user);
            user = userService.getUserInfo(user.getOpen_id());
            try {
                userDao.updInvitationCode(user.getOpen_id(),ShareCodeUtil.toSerialCode(user.getUser_id()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            //把新用户信息存入Redis
            stringRedisTemplate.opsForValue().set(user.getOpen_id(),JSONObject.toJSONString(user));
            return new MassageJsons("0","登录成功",user);
        }
    }

    @RequestMapping("/random")
    public String random(String user_phone){
        System.out.println(user_phone);
        String random = "";
        for (int i=0;i<6;i++){
            random+=new Random().nextInt(10);
        }
        //给手机号发送验证码
        SendSms.sendCode(user_phone,random);
        System.out.println(random);
        return random;

    }
    //绑定手机号
    @RequestMapping("/getPhone")
    public MassageJsons udpUserPhoneInfo(String open_id,String user_phone){

        return userService.addUserPhoneInfo(open_id,user_phone);
    }
    @RequestMapping("/getuser")
    //user_pid     user_phone
    public MassageJsons getUser(String open_id,String user_phone){
        //从数据查询该用户
        User user = userService.getUserInfo(open_id);
        System.out.println(user.toString()+"+++++++++++++++++++++++++++++++++");

        //如果手机号为空
        if(user.getUser_phone()==null){
            //从缓存查询是否是从邀请页过来的用户
            String jsonMap = stringRedisTemplate.opsForValue().get(user_phone);
            //如果不为空则是
            if(jsonMap!=null){
                //把被邀请过来的用户信息转换为Map对象
                HashMap<String,String> map = JSONObject.parseObject(jsonMap,HashMap.class);
                //获取邀请人的id
                String user_pid = map.get("user_pid");
                //获取被邀请人的手机号
                String user_phones = map.get("user_phone");

                
                //根据传入过来的邀请人id查询邀请人信息
                User puser = userDao.getUserInfoUid(user_pid);
/*                //把邀请人的id存入当前用户的父级id里
                user.setUser_pid(Long.parseLong(user_pid));*/

                try {
                    userDao.updUserUserPid(user.getUser_id(),puser.getUser_id());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //给当前用户赋代理等级
                Integer proxy_id = puser.getProxy_id() == 1 ? 2 : 3;
                //更新当前用户的代理id
                try {
                    System.out.println(user.getUser_id()+"-----------"+proxy_id);
                    userDao.updUserProxyId(user.getUser_id(),proxy_id);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //绑定完成之后删除缓存
                stringRedisTemplate.delete(user_phone);
            }

            //存入用户绑定的手机号
            user.setUser_phone(user_phone);
            //则绑定该手机号
            userService.addUserPhoneInfo(open_id,user_phone);
            //重新查询最新用户信息
            user = userDao.getUserInfoUid(user.getUser_id()+"");
        }
        //更新Redis里的用户对象
        stringRedisTemplate.opsForValue().set(open_id,JSONObject.toJSONString(user));
        return new MassageJsons("0","绑定成功",user);
    }
    @RequestMapping("/getUserById")
    public MassageJsons getUserById(Long user_id){
        User user = null;
        try {
            user = userService.getUserById(user_id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(user!=null){
            return new MassageJsons("0","请求成功",user);
        }
        return null;
    }
    @RequestMapping("/updUserName")
    public MassageJsons updUserName(String user_name,String open_id){
        //更改用户名称并存入缓存
        User user = null;
        try {
            userService.updUserName(user_name,open_id);
            String userjson = stringRedisTemplate.opsForValue().get(open_id);
            user = JSONObject.parseObject(userjson,User.class);
            user.setUser_name(user_name);
            stringRedisTemplate.opsForValue().set(open_id,JSONObject.toJSONString(user));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new MassageJsons("0","更改成功",user);
    }

    /**
     * 获取直推用户
     * @param user_id
     * @return
     */
    @RequestMapping("/getDirect")
    public MassageJson getDirect(Long user_id){
        int count = 0;
        List<User> userList = null;
        try {
            userList = userService.getDirect(user_id);
            for (int i =0;i<userList.size();i++){
                //用直推用户id当作父级id查询他的下级代理信息
                List<User> userLists = userService.getDirect(userList.get(i).getUser_id());
                count+=userLists.size();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回直推间推人数 code直推人数     data间推人数
        return new MassageJson(userList.size(),"请求成功",count);

    }

    /**
     * 获取间推总人数
     * @param user_id
     * @return
     */
    @RequestMapping("/getInDirect")
    public MassageJsons getInDirect(Long user_id){
        //间推总人数
        int count = 0;
        try {
            //先获取直推用户信息
            List<User> userList = userService.getDirect(user_id);
            for (int i =0;i<userList.size();i++){
                //用直推用户id当作父级id查询他的下级代理信息
                List<User> userLists = userService.getDirect(userList.get(i).getUser_id());
                count+=userLists.size();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new MassageJsons("0","请求成功",count);
    }

    /**
     * 更改用户头像
     * @return
     */
    @RequestMapping("/updUserIcon")
    public MassageJsons updUserIcon(@RequestBody HashMap<String,String> hashMap){
        //String IconPath,String open_id
        //1.获取到后面到数据
        String base64Data =  hashMap.get("IconPath").split(",")[0];
         // 2.解码成字节数组
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(base64Data);
        //3.字节流转文件
        FileOutputStream fos = null;
        try {
            User user = null;
            String fileName = "D:\\"+UUID.randomUUID()+".jpg";
            fos = new FileOutputStream(fileName);
            fos.write(bytes);
            File file = new File(fileName);
            MultipartFile multipartFile = null;
            InputStream inputStream = null;
            try {
                inputStream = new FileInputStream(file);
                multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
                picUploadService.upload(multipartFile,hashMap.get("open_id"));
                user=userService.getUserInfo(hashMap.get("open_id"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new MassageJsons("0","修改成功",user);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return new MassageJsons("1","修改失败");
    }

    @Autowired
    private PicUploadService picUploadService;

    @RequestMapping("/ceshi")
    public PicUploadResult ceshi(){
        File file = new File("D:\\aaa.jpg");
        MultipartFile multipartFile = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return picUploadService.upload(multipartFile,"oc4Qm0WnQmE0TIdBrOV7S0iuCIF8");
    }
}

